/*Start From Here*/

var lineOptions = {
    chart: {
        renderTo: 'lineChart',
        defaultSeriesType: 'line',
    },
    colors: ['#50B432','#ED561B'],
    title: {
        text: 'Fortnight Job Line Chart',
        x: -20
    },
    subtitle: {
        text: '',
        x: -20
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
            month: '%e. %b',
            year: '%b'
        },
        title: {
            text: ''
        }
    },
    yAxis: {
        title: {
            text: 'Count'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    /*Display all the series on one tooltip*/
    tooltip: {
        shared: true,
        crosshairs: true
    },
    credits: {
        enabled: false
    },
    series: [
        {name: 'Success'},
        {name:'Fail'}
    ]
}

var pieOptions ={
    chart:{
        renderTo:'pieChart',
        defaultSeriesType:'pie'
    },
    colors: ['#50B432','#ED561B'],
    title:{
        text:'All Job Pie Chart',
        x:-20
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: false
            },
            showInLegend: true
        }
    },
    credits: {
        enabled: false
    },
    series: [
        {name: 'ALL Jobs'}
    ]
}

$(function () {
    /*User -- HardCode for 21tester*/
    if($('#usr').val() == "21tester")
    {
        var username = $('#usr').val();
        $('#loginForm').hide();
        var helloForm = "<span id='helloForm'><span class='btn btn-danger navbar-right' onclick='Logout()' style='color:white;margin-top: 8px'>LogOut</span><span class='navbar-right' style='color:white;margin-right: 15px;font-size:20px;margin-top: 11px'>Hello, " + username + " </span></span>";
        $('#navbar').append(helloForm);
    }

    //
    ///*Generate Random Image Background*/
    //var fileName = "images/cake" + getRandom(4) + ".jpg";
    //$('#BackImageDiv').css("background-image","url(" + fileName + ")" );

    /*Job Table double click event*/
    $('#JobTable').on('dbl-click-row.bs.table', function (e, row, $element) {
        if(row['failCount'] > 0) {
            window.open("CaseList.php?jobid=" + row["id"] + "&status=0");
        }
        else {
            window.open("CaseList.php?jobid=" + row["id"]+ "&status=1")
        }
    })

    /*Server List*/
    $.ajax({
        type: "GET",
        url: "getTestServer.php",
        success: function(data) {
            /*From String to Json*/
            data = JSON.parse(data);
            $.each(data, function(idx, obj) {
                var opt = obj.category;
                var ip = obj.ip;

                /*My Local Server*/
                if(ip == "192.168.2.191") {
                    $('#'+opt).append("<option data-subtext='common'>" + ip + "</option>");
                }
                else {
                    $('#'+opt).append("<option>" + ip + "</option>");
                }
            });
            /*Refresh Selecter*/
            $('#SelectServer').selectpicker('refresh');
        }})

    /*Init the chart*/
    $.ajax({
        type:"GET",
        url:'getLineChartData.php',
        success: function(tsv){
            var successData = [];
            var failData = [];
            var successCount = 0;
            var failCount = 0;
            try {
                // split the data return into lines and parse them
                tsv = tsv.split(/\n/g);
                jQuery.each(tsv, function(i, line) {
                    if(line[1] != null) {
                        line = line.split(/\t/);
                        var date = Date.parse(line[0] + ' UTC');
                        successData.push([date, parseInt(line[1].replace(',', ''), 10)]);
                        failData.push([date, parseInt(line[2].replace(',', ''), 10)]);

                        successCount = successCount + parseInt(line[1]);
                        failCount = failCount + parseInt(line[2]);
                    }
                });
            } catch (e) {  }
            lineOptions.series[0].data = successData;
            lineOptions.series[1].data = failData;
            var lineChart = new Highcharts.Chart(lineOptions);

            var pieData = [];
            var successPieData = {name:'Success', y:successCount};
            var failPieData = {name:'Fail', y:failCount};
            pieData.push(successPieData);
            pieData.push(failPieData);
            pieOptions.series[0].data = pieData;
            var pieChart = new Highcharts.chart(pieOptions);


        }
    });
});



/*Logout*/
function Logout(){
    $.ajax({
        type: "POST",
        url: "LogOut.php",
        success: function(data) {
            if (data == "Success") {
                /*Remove Login Information*/
                $('#helloForm').remove();
                /*Show Login Form*/
                $('#loginForm').show();
                /*Clear User Information*/
                $('#usr').val("");
            }
            else {
                alert ("Logout Error!");
            }
        }
    })
}

/*Run Job*/
function goRun()
{
    $("#MessageText").html("");

    if($('#SelectServer').val() == "")
    {
        var htmlString = "<div style=\"height: auto; padding: 8px;margin:0px;border: 0px;border-radius: 5px;\" class=\"alert alert-danger\" role=\"alert\"><strong>Please select one server!</strong></div>";
        $("#LoadingDiv").html("");
        $("#MessageText").html(htmlString).hide().fadeIn(2000);
    }
    else
    {
        /*Invoke PHP script*/
        var serverIP = $('#SelectServer').val();
        /*For multiple-server use*/
        var serverHost = "serverHost=" + serverIP;

        var domain = $("#domain").val()

        if (domain == "") {
            domain = "appv3.api.test.join10.com";
        }
        /*Ajax Call*/
        $.ajax({
            type: "Get",
            url: "apache-jmeter-2.13/bin/Run.php?domain=" + domain,
            beforeSend:LoadGIF(),
            success: function(data) {
                /*Success*/
                if(data == 0) {
                    var htmlString = "<div style=\"height: auto; padding: 8px;margin:0px;border: 0px;border-radius: 5px;\" class=\"alert alert-success\" role=\"alert\"><strong>Well Done!</strong></div>";
                    $("#LoadingDiv").html("");
                    $("#MessageText").html(htmlString).hide().fadeIn(1000);
                    /*Refresh Job Table*/
                    $('#JobTable').bootstrapTable('refresh');

                }
                /*Fail*/
                else {
                    var htmlString = "<div style=\"height: auto; padding: 8px;margin:0px;border: 0px;border-radius: 5px;\" class=\"alert alert-danger\" role=\"alert\"><strong>Error in RUN!</strong></div>";
                    $("#LoadingDiv").html("");
                    $("#MessageText").html(htmlString);
                }
            }
        });

    }
}

/*Load GIF*/
function LoadGIF()
{
    var htmlString = "<i class=\"icon-spinner icon-spin icon-2x pull-left\"></i>";
    $("#LoadingDiv").html(htmlString);
}

/*Row Styles For Job Table*/
function rowStyle(row, index) {
    /*define five type*/
    var classes = ['active', 'success', 'info', 'warning', 'danger'];

    /*if has error*/
    if (row["failCount"] > 0) {
        return {
            classes: classes[4]
        };
    }
    /*if no error*/
    else if (row["failCount"] == 0)
    {
        return {
            classes: classes[1]
        };
    }
    /*for old data --- no fail column*/
    else if (row["failCount"] == "" || row["failCount"] == null)
    {
        return{
            classes: classes[3]
        }
    }
    /*default*/
    return {};
}

/*Get Random Number For Background Images*/
function getRandom(n){
    return Math.floor(Math.random()*n+1)
}